<html>
<head>
<title>比赛数据采集</title>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style>
body{font-size:12px;overflow-y:auto;overflow-x:hidden; margin:0; padding:0;}
td{font-size:12px;}
</style>
</head>
<!--
<form action="#">
	<input type="text" name="date">
	<input type="submit" value="查询">
</form>
-->
<?php
include_once 'module/simple_html_dom.php';

date_default_timezone_set("Asia/Shanghai");

$date = @ $_GET["date"];
$showDate = null;

if ($date == "") {
	$showDate = date('Y-m-d H:i');
	$date = date("Y-m-d");
} else {
	$showDate = date("Y-m-d H:i", strtotime($date . " day"));
	$date = date("Y-m-d", strtotime($date . " day"));
}

//网易体育取得国际足球数据
$url = "http://goal.sports.163.com/schedule/" . str_replace("-", "", $date) . ".html";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
$footballMatchListHTML = curl_exec($ch);
curl_close($ch);
$footballMatchListHTML = str_get_html($footballMatchListHTML);

$optaIds = NULL;

$c1 = $footballMatchListHTML->find('span[class=c1] a');
$c2 = $footballMatchListHTML->find('span[class=c2] a');
$optaIds = $footballMatchListHTML->find('tr[class=goal]');

//新浪体育取得比赛列表
$url = "http://match.sports.sina.com.cn/livecast/show_date.php?date=" . $date . "&t=" . rand();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
$matchListHTML = curl_exec($ch);
curl_close($ch);
$matchListHTML = str_get_html($matchListHTML);

$sql = "INSERT INTO live_match (matchId,matchName, matchTime, matchCategory, matchStatus, matchRecord, matchTv, matchEvent, visitTeam, visitTeamPic, visitTeamScore, homeTeam, homeTeamPic, homeTeamScore, matchUrl, matchOpta, matchOptaId, matchOptaSeason, matchOptaRound, matchEazy) VALUES";

$mathcIds = "''";

$matchIndex = 0;

foreach ($matchListHTML->find('table[class=tab_01]') as $index => $matchTable) {

	$matchCategory = $index +1;
	//循环区的赛事信息
	foreach ($matchTable->find('tr') as $matchTr) {
		$matchEazy = "0";
		//判断分类下时候存在赛事，并且过滤不符合采集规范的赛事（如赛车比赛）
		if (count($matchTr->find('td')) > 0) {

			//取得赛事时间
			$time = $matchTr->find('td[class=b]', 0)->innertext;
			$matchTime = $date . " " . $time;

			//取得赛事状态
			$matchStatus = $matchTr->find('td[class=e]', 0)->innertext;
			$matchStatus = substr($matchStatus, 0, 6);

			//有比赛队伍
			if ($matchTr->find('td[class=d] div span', 0) != null) {

				//区的赛事名称
				$matchName = $matchTr->find('td[class=c]', 0)->innertext;

				//区的赛事主队名称
				$homeTeam = $matchTr->find('td[class=d] div span', 0);

				//赛事直播受欢迎标志
				if ($homeTeam->find('a[class=hot]', 0) == null) {
					$matchEazy = "1";
				}
				//主队名称
				$homeTeam = $matchTr->find('td[class=d] div span', 0)->find('a', 0)->innertext;
				//取得赛事主队图片
				$homeTeamPic = $matchTr->find('td[class=d] div img[class=dc2]', 0)->src;
				//取得赛事地址
				$matchUrl = $matchTr->find('td[class=d] div span', 1)->find('a', 0);
				//取得赛事比分
				if ($matchUrl) {
					$TeamScore = $matchTr->find('td[class=d] div span', 1)->find('a', 0)->innertext;
				} else {
					$TeamScore = $matchTr->find('td[class=d] div span', 1)->innertext;
				}
				$TeamScore = str_replace(" ", "", $TeamScore);
				if ($TeamScore == 'VS' || $TeamScore == 'vs') {
					//取得赛事主队比分
					$homeTeamScore = 0;
					//取得赛事客队比分
					$visitTeamScore = 0;
				} else {
					$TeamScore = explode("-", $TeamScore);
					//取得赛事主队比分
					$homeTeamScore = $TeamScore[0];
					//取得赛事客队比分
					$visitTeamScore = $TeamScore[1];
				}
				//取得赛事客队图片
				$visitTeamPic = $matchTr->find('td[class=d] div img[class=dc3]', 0)->src;
				//取得赛事客队名称
				$visitTeam = $matchTr->find('td[class=d] div span', 2);
				//赛事直播受欢迎标志
				if ($visitTeam->find('a[class=hot]', 0) == null) {
					$matchEazy = "1";
				}
				$visitTeam = $matchTr->find('td[class=d] div span', 2)->find('a', 0)->innertext;
				$matchEvent = 'N';
			} else {
				$homeTeam = '';
				$homeTeamPic = '';
				$homeTeamScore = '';
				$visitTeam = '';
				$visitTeamPic = '';
				$visitTeamScore = '';
				//区的赛事名称
				$matchName = $matchTr->find('td[class=d] div a', 0)->innertext;
				//取得赛事地址
				$matchUrl = $matchTr->find('td[class=d] div a', 0);
				$matchEvent = 'Y';
			}

			//取得赛事记录类型
			$matchRecord = $matchTr->find('td[class=f]', 0)->innertext;
			if ($matchRecord == " " || strpos($matchTr->find('td[class=d] div span', 1), "shtml")) {
				//确认为无直播信息
				$matchRecord = null;
				//遇到无效赛事地址，赛事地址清空
				$matchUrl = null;
			} else
				if (strpos($matchName, "CBA") && $matchEazy == "1") {
					//当CBA比赛不是热门赛事，则确认是无直播信息
					$matchRecord = null;
					$matchUrl = null;
				} else {
					//echo $matchName;
					$matchRecord = $matchTr->find('td[class=f] a', 0)->innertext;
				}

			//取得赛事直播
			$matchTv = $matchTr->find('td[class=g]', 0)->innertext;

			//生成赛事ID(2011123101)
			$matchId = (intval(str_replace("-","",$date))+1000) . str_pad($matchIndex++, 2, "0", STR_PAD_LEFT);
			
			//echo $matchId."<br>";

			//OPTA设置
			$matchOpta = "N";
			$matchOptaId = NULL;
			$matchOptaSeason = NULL;
			$matchOptaRound = NULL;

			if ($matchRecord != null) {
				if ($matchUrl->href != null) {
					$matchUrl = $matchUrl->href;
					$matchId = explode("?", $matchUrl);
				} else {
					$matchUrl = $matchUrl->onclick;
					$matchUrl = explode("return popup('", $matchUrl);
					$matchUrl = explode("');", $matchUrl[1]);
					$matchUrl = $matchUrl[0];
					$matchId = explode("?", $matchUrl);
				}
				$matchId = $matchId[1];
				$matchId = explode("id=", $matchId);
				if (count($matchId) == 1) {
					$matchId = $matchId[0];
				} else {
					$matchId = $matchId[1];
				}
				$matchId = explode("\"", $matchId);
				$matchId = $matchId[0];
				$matchId = explode("'", $matchId);
				$matchId = $matchId[0];
				$matchId = explode("&", $matchId);
				$matchId = $matchId[0];

				//如果是国际足球赛事，取得OPTA_ID
				if ($matchCategory == "2") {
					$matchRecordTemp = trim(iconv("gb2312", "UTF-8", $matchRecord));
					if ($matchRecordTemp == "实录" || $matchRecordTemp == "直播间") {
						$optaMatchCount = count($c1);
						$optaFlg = true;
						for ($i = 0; $i < $optaMatchCount; $i++) {
							if (iconv("gb2312", "UTF-8", $homeTeam) == $c1[$i]->innertext || iconv("gb2312", "UTF-8", $visitTeam) == $c2[$i]->innertext) {
								$matchOptaId = $optaIds[$i]->id;
								$matchOptaId = explode('_', $matchOptaId);
								$matchOptaRound = $matchOptaId[2];
								$matchOptaSeason = $matchOptaId[3];
								$matchOptaId = $matchOptaId[1];
								$matchOpta = "Y";
								$optaFlg = false;
								break;
							}else{
								$matchOpta = "N";
							}
						}
						if ($optaFlg) {
							$matchOpta = file_get_contents("http://match.sports.sina.com.cn/livecast/g/live.php?id=" . $matchId, null, null, "580", "340");

							//判断OPTA数据是否存在
							if (strpos($matchOpta, "opta_id")) {

								$matchOpta = str_replace(" ", "", $matchOpta);
								$matchOpta = explode("opta_id='", $matchOpta);
								$matchOpta = explode("';", $matchOpta[1]);
								$matchOptaId = $matchOpta[0];
								$matchOpta = "Y";
							}
						}
					}
				}
			}
			$sql .= "('" . $matchId . "', '" . $matchName . "', '" . $matchTime . "', '" . $matchCategory . "', '" . $matchStatus . "', '" . $matchRecord . "', '" . $matchTv . "', '" . $matchEvent . "', '" . $visitTeam . "', '" . $visitTeamPic . "', '" . $visitTeamScore . "', '" . $homeTeam . "', '" . $homeTeamPic . "', '" . $homeTeamScore . "', '" . $matchUrl . "', '" . $matchOpta . "', '" . $matchOptaId . "', '" . $matchOptaSeason . "', '" . $matchOptaRound . "', '" . $matchEazy . "'),";
			$mathcIds .= ",'" . $matchId . "'";
		}
	}
}

//连接数据库
$config = require 'conf/config.ini.php'; //加载公用config.ini.php
$conn = mysqli_connect($config["DB_HOST"], $config["DB_USER"], $config["DB_PWD"], $config["DB_NAME"]);


//插入比赛比分
if ($matchIndex > 0) {

	$sql = "SET NAMES gbk;" .
	"delete from live_match " .
	"where 	matchTime >= '" . $date . "' ".
	"and	matchTime < date_add('".$date."',INTERVAL 1 day); ".
	"delete from live_match where matchId in (" . $mathcIds . ");" .
	substr($sql, 0, strlen($sql) - 1) . ";";
	//插入比赛比分
	mysqli_multi_query($conn, $sql);
}


//echo iconv("gb2312", "UTF-8", $sql);

sleep(1);

//再检索
$conn = mysqli_connect($config["DB_HOST"], $config["DB_USER"], $config["DB_PWD"], $config["DB_NAME"]);
$sql = "select * from live_match  ";
$sql .= "where 	matchTime >= '" . $date . "' ";
$sql .= "and	matchTime < date_add('".$date."',INTERVAL 1 day) ";
$sql .= "order by matchTime,matchCategory";
mysqli_query($conn, "SET NAMES utf8");
$matchList = mysqli_query($conn, $sql);

//echo mysqli_num_rows($matchList);

echo '<div style="text-align:center">' . $showDate . '</div>';
echo '<table width="100%">';
while ($match = mysqli_fetch_object($matchList)) {
	echo '<tr>';
	echo '	<td align="center">' . $match->matchStatus . '</td>';
	echo '	<td align="center" rowspan="2">' . $match->matchName . '</td>';
	echo '	<td align="right">' . $match->homeTeam . '</td>';
	echo '	<td align="center">' . $match->homeTeamScore . '</td>';
	echo '</tr>';
	echo '<tr>';
	echo '	<td align="center">' . substr($match->matchTime, 11, 13) . '</td>';
	echo '	<td align="right">' . $match->visitTeam . '</td>';
	echo '	<td align="center">' . $match->visitTeamScore . '</td>';
	echo '</tr>';
}
echo '</table>';
?>
</html>
